import 'dart:async';

import 'package:async/async.dart';

import '../common/test_page.dart';

class ByteCollectionTestPage extends TestPage {
  ByteCollectionTestPage(super.title) {
    test('collectBytes()简单列表和溢出', () {
      var result = collectBytes(Stream.fromIterable([
        [0],
        [1],
        [2],
        [256]
      ]));
      expect(result);
    });

    test('collectBytes()无事件', () {
      var result = collectBytes(Stream.fromIterable([]));
      expect(result);
    });

    test('collectBytes()空事件', () {
      var result = collectBytes(Stream.fromIterable([[], []]));
      expect(result);
    });

    test('collectBytes()错误事件', () {
      var result = collectBytes(Stream.fromIterable(
          Iterable.generate(3, (n) => n == 2 ? throw 'badness' : [n])));
      expect(result);
    });

    test('collectBytesCancelable()简单列表和溢出', () {
      var result = collectBytesCancelable(Stream.fromIterable([
        [0],
        [1],
        [2],
        [256]
      ]));
      expect(result.value);
    });

    test('collectBytesCancelable()无事件', () {
      var result = collectBytesCancelable(Stream.fromIterable([]));
      expect(result.value);
    });

    test('collectBytesCancelable()空事件', () {
      var result = collectBytesCancelable(Stream.fromIterable([[], []]));
      expect(result.value);
    });

    test('collectBytesCancelable()错误事件', () {
      var result = collectBytesCancelable(Stream.fromIterable(
          Iterable.generate(3, (n) => n == 2 ? throw 'badness' : [n])));
      expect(result.value);
    });

    test('collectBytesCancelable().value.whenComplete, collectBytesCancelable().cancel()取消', () async {
      var sc = StreamController<List<int>>();
      var result = collectBytesCancelable(sc.stream);
      result.value.whenComplete(() {});

      expect(sc.hasListener);
      sc.add([1, 2]);
      await nextTimerTick();
      expect(sc.hasListener);
      sc.add([3, 4]);
      await nextTimerTick();
      expect(sc.hasListener);
      result.cancel();
      expect(sc.hasListener); // Cancelled immediately.
      var replacement = await result.valueOrCancellation();
      expect(replacement);
      await nextTimerTick();
      sc.close();
      await nextTimerTick();
    });
  }

}

Future nextTimerTick() => Future(() {});